﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Mysoft.Common.Response;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mysoft.AppStartup.Container
{
    /// <summary>
    /// 实体模型验证路由
    /// </summary>
    public class ModelStateFilter
    {

        public static void Register(IServiceCollection services) {

            services.Configure<ApiBehaviorOptions>(options =>
            {
               
                options.InvalidModelStateResponseFactory = (context) =>
                {
                    StringBuilder smsg = new StringBuilder();
                    foreach (var key in context.ModelState.Keys)
                    {
                        var errors = context.ModelState[key].Errors;
                        if (errors.Count() > 0)
                        {
                            if (smsg.Length > 0) 
                            {
                                smsg.Append("、");
                            }
                            smsg.Append(errors[0].ErrorMessage);
                        }
                    }

                    return new JsonResult(new ErrorResponse() { code = 403, success = false, message = $"参数验证不通过:{smsg}" });
                };
            });

        }
     
    }
}
